package com.zzty.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zzty.common.GunZip;
import com.zzty.common.PropertyUtil;
import com.zzty.entity.TeamExamTransaction;
import com.zzty.entity.User;
import com.zzty.service.GroupService;
import com.zzty.service.TeamExamService;
import com.zzty.service.TeamExamTransactionService;
import com.zzty.serviceimpl.GroupServiceImpl;
import com.zzty.serviceimpl.TeamExamServiceImpl;
import com.zzty.serviceimpl.TeamExamTransactionServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;



@WebServlet(name="/UploadServlet",urlPatterns = "/UploadServlet")
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    // 上传文件存储目录
    // 上传配置
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB
    TeamExamTransactionService tets=new TeamExamTransactionServiceImpl();
    TeamExamService tes=new TeamExamServiceImpl();
    GroupService gs=new GroupServiceImpl();

    GunZip gunZip=new GunZip();
    static PropertyUtil props=new PropertyUtil();
    /**
     * 上传数据及保存文件
     */
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        // 检测是否为多媒体上传
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 如果不是则停止
            PrintWriter writer = response.getWriter();
            writer.println("Error: 表单必须包含 enctype=multipart/form-data");
            writer.flush();
            return;
        }
        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // 设置临时存储目录
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 设置最大文件上传值
        upload.setFileSizeMax(MAX_FILE_SIZE);
        // 设置最大请求值 (包含文件和表单数据)
        upload.setSizeMax(MAX_REQUEST_SIZE);
        // 中文处理
        upload.setHeaderEncoding("UTF-8");
        User user=(User)request.getSession().getAttribute("user");
        String userName=user.getName();
        String userNames=gs.getUserNamesByUserName(userName);
        Calendar cal = Calendar.getInstance();
        userNames+=cal.get(Calendar.YEAR)+"_"+(cal.get(Calendar.MONTH)+1)+"_"+cal.get(Calendar.DAY_OF_MONTH);
        String filePath1 = props.getProp().getProperty("path.zip");
        File storeFile = new File(filePath1);
        if (!storeFile.exists()) {
            storeFile.mkdir();
        }
        String filePath2 =filePath1+"//"+ userNames+".zip";
        File sFile=new File(filePath2);
        List<FileItem> formItems = null;
        try {
            formItems = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        if (formItems != null && formItems.size() > 0) {
                for (FileItem item : formItems){
                    if (!item.isFormField()){
                        try {
                            item.write(sFile);
                        } catch (Exception e){
                            e.printStackTrace();
                        }
                        System.out.println(filePath2);
                        String gunZipPath=props.getProp().getProperty("path.team")+"//"+userNames;
                        String filePath3=gunZip.uncompress(filePath2,gunZipPath);
                        updateTeamExamTransaction(request,response,filePath3,cal);
                    }
                }
            }


    }
    protected void updateTeamExamTransaction(HttpServletRequest request,
                          HttpServletResponse response,String filePath,Calendar cal) throws ServletException, IOException {
        TeamExamTransaction teamExamTransaction=new TeamExamTransaction();
        teamExamTransaction.setTeamExamId(tes.getIdByDate());
        teamExamTransaction.setAnswerUrl(filePath);
        User user=(User)request.getSession().getAttribute("user");
        String userName=user.getName();
        teamExamTransaction.setGroupId(gs.getIdByUserName(userName));
        boolean result = false;
        result = tets.updateTeamExamTransactionByUserId(teamExamTransaction, cal);
        System.out.println("result=" + result);
        response.setContentType("text/html; charset=UTF-8");
        response.sendRedirect("jsp/selfHistoryGroup.jsp");
//        getServletContext().getRequestDispatcher("/jsp/selfHistoryGroup.jsp").forward(
//                request, response);这样跳转只是后台跳转，前端地址不变，即还是servlet的地址
    }
}